<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';
import { formatNumber } from '@/home/utils/format';
import { useFetch } from '@/home/hooks/fetch';
import Pagination from '@/home/components/Pagination.vue';
import LoadingBox from '@/home/components/LoadingBox.vue';
import Loading from '@/home/components/Loading.vue';
import Tag from '@/home/components/Tag.vue';
import SearchSelect from '@/home/components/SearchSelect.vue';
import { useI18n } from 'vue-i18n';
import { gotoUrl } from '@/home/utils/other';
import { getShortDate } from '@/home/utils/date';

const props = defineProps({
  query: {
    type: String,
    default: '',
  },

  type: {
    type: String,
    default: 'search',
  },
});

// 专栏不分页
const PAGE_SIZE = props.type === 'column' ? 999 : 10;
const atomgitUrl = import.meta.env.VITE_ATOMGIT_URL;

const { $fetch } = useFetch();
const { t } = useI18n();

const page = ref(1);
const listing = ref<Record<string, any>[]>([]);
const loading = ref(true);
const total = ref(0);
const orderType = ref<'newest' | 'hottest'>('newest');

const orderOptions = [
  { label: t('home.search.order.newest'), value: 'newest' },
  { label: t('home.search.order.hottest'), value: 'hottest' },
];

const refresh = async () => {
  loading.value = true;

  // 目前只有资讯支持专栏

  const params: Record<string, any> = {
    productType: 'journalism',
    pageNum: page.value,
    pageSize: PAGE_SIZE,
  };

  const queryParam = props.type === 'tag'
    ? { searchLabel: props.query, strSort: orderType.value }
    : props.type === 'column'
      ? { columnId: props.query, pageSize: PAGE_SIZE }
      : { keyWords: props.query, strSort: orderType.value };

  const { isSuccess, data } = await $fetch('/esInfoProduct/getPageProduct', {
    method: 'post',
    data: { ...params, ...queryParam },
  });

  loading.value = false;

  if (isSuccess) {
    listing.value = data?.records ?? [];
    total.value = data?.total ?? 0;
  }
}

const pageChange = (index: number) => {
  page.value = index;

  refresh();
}

watch(() => props.query, () => {
  page.value = 1;
  refresh();
});

onMounted(() => {
  refresh();
});
</script>

<template>
  <div class="page-search-journalism container">
    <div class="mb-8 flex-y-center justify-between" v-if="props.type !== 'column'">
      <SearchSelect v-model="orderType" :options="orderOptions" @change="() => refresh()" />
      <div class="text-12 text-#adadad leading-20" v-if="props.type !== 'tag'">{{ $t('home.search.searchResult', { total }) }}</div>
    </div>

    <ul class="min-h-150 rounded-6 bg-white">
      <LoadingBox :loading="loading">
        <template v-if="listing?.length > 0">
          <li class="group" v-for="item in listing" :key="item.productId">
            <RouterLink :to="`/explore/journalism/detail/${item.productId}`" custom v-slot="{ href }">
              <div class="flex cursor-pointer justify-between gap-x-20 px-24 py-16 hover:(bg-[rgba(61,124,250,0.03)]) group-first:(pt-24) group-last:(pb-24)" @click="gotoUrl(href)">
                <div class="flex-grow">
                  <div class="flex-y-center flex-wrap gap-x-4 text-12 text-[#adadad] leading-20">
                    <a :href="`${atomgitUrl}/${item.username}`" target="_blank" class="flex-y-center gap-x-4" @click.stop>
                      <img
                        :data-src="item.photo"
                        :alt="item.nickname"
                        class="lozad block size-20 border border-#e8e8e8 rounded-50% border-solid"
                        v-if="item.photo"
                      >
                      <div class="text-#292929">{{ item.nickname }}</div>
                    </a>
                    <div>·</div>
                    <div>{{ getShortDate(item.publishTime) }}</div>
                    <template v-for="(labelValue, labelIndex) in item.labelList" :key="labelValue.labelId">
                      <div v-if="labelIndex === 0">|</div>
                      <div v-else>·</div>
                      <Tag
                        :id="labelValue.labelId"
                        :name="labelValue.labelName"
                        :hashtag="false"
                        class="hover:(text-#292929)"
                        :class="{ 'text-#3D7CFA': (props.type === 'tag' && (labelValue.labelId == props.query)) }"
                        blank
                      />
                    </template>
                  </div>

                  <RouterLink :to="`/explore/journalism/detail/${item.productId}`" class="mt-8 block" target="_blank">
                    <!-- eslint-disable-next-line vue/no-v-html -->
                    <h3 class="line-clamp-1 break-anywhere text-16 color-#292929 font-medium leading-24" v-html="item.title"></h3>
                  </RouterLink>

                  <!-- eslint-disable-next-line vue/no-v-html -->
                  <p class="line-clamp-1 mt-4 break-anywhere text-14 color-#575757 leading-22" v-html="item.body"></p>

                  <div class="mt-8 flex-y-center gap-x-24 text-#575757">
                    <div class="flex-y-center gap-4 text-12">
                      <span class="i-icons:eye-outlined size-16"></span>
                      <span class="leading-16">{{ formatNumber(item.viewCount) }}</span>
                    </div>
                    <div class="flex-y-center gap-4 text-12">
                      <span class="i-icons:good size-16"></span>
                      <span class="leading-16">{{ formatNumber(item.likeCount) }}</span>
                    </div>
                    <div class="flex-y-center gap-4 text-12">
                      <span class="i-icons:comment-outlined-2 size-16"></span>
                      <span class="leading-16">{{ formatNumber(item.commentCount) }}</span>
                    </div>
                  </div>
                </div>

                <div class="h-74 w-126 flex-shrink-0 self-end" v-if="item.coverUrl">
                  <img :data-src="item.coverUrl" :alt="item.title" class="lozad size-full rounded-4 bg-#f7f7f7 object-contain">
                </div>
              </div>
            </RouterLink>

            <hr class="mx-24 h-1 border-#fafafa border-solid group-last:(hidden)">
          </li>
        </template>
        <template v-else-if="!loading && listing?.length === 0">
          <li class="min-h-550 flex items-center justify-center color-#8b8b8b">{{ $t('home.common.emptyContent') }}</li>
        </template>

        <template #loading>
          <li class="min-h-100 flex items-center justify-center">
            <Loading class="size-16 color-#8b8b8b" />
          </li>
        </template>
      </LoadingBox>
    </ul>

    <Pagination class="data-[total-pages=gt1]:(mt-32)" :count="total" :page="page" :page-size="PAGE_SIZE" @change="pageChange" />
  </div>
</template>

<style lang="scss" scoped>
</style>
